package com.sc.VenusQueryBeta.ui.activites.login;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.dou361.dialogui.DialogUIUtils;
import com.dou361.dialogui.listener.DialogUIListener;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.activity.BaseMVPCompatActivity;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.hengjun.kingstar.sdk.widgets.ClearEditText;
import com.hengjun.kingstar.sdk.widgets.CountDownButton;
import com.hengjun.kingstar.sdk.widgets.TipHelper;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.contract.login.ForgotPasswordContract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.login.RegisterVerticationBean;
import com.sc.VenusQueryBeta.presenter.login.ForgotPasswordPresenter;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 忘记密码Activity
 */
public class ForgotPasswordActivity extends BaseMVPCompatActivity<ForgotPasswordContract.ForgotPasswordPresenter> implements ForgotPasswordContract.IForgotPasswordView {

    @BindView(R.id.changepassword_back)
    ImageButton changepasswordBack;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.about_kingstar_infornation)
    AppBarLayout aboutKingstarInfornation;
    @BindView(R.id.tv_country_name)
    TextView tvCountryName;
    @BindView(R.id.tv_number_phone)
    TextView tvNumberPhone;
    @BindView(R.id.phone_register)
    ClearEditText phoneRegister;
    @BindView(R.id.get_number)
    ClearEditText getNumber;
    @BindView(R.id.register_next)
    Button registerNext;
    @BindView(R.id.btn_register_number)
    CountDownButton btnRegisterNumber;
    @BindView(R.id.sv_main)
    ScrollView svMain;

    private PopupWindow popupWindow;
    private TextView countryDalu;
    private TextView countryMacao;
    private TextView countryHk;
    private TextView countryTw;
    private TextView countryOther;
    private String s;
    private Drawable img;
    private String deviceUid;//设备id
    private String countryCode = "1";//澳门
    private String ver;


    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return ForgotPasswordPresenter.newInstance();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_forgot_password;
    }

    /**
     * 點擊彈出小窗口
     */
    @SuppressLint("WrongConstant")
    private void inputOtherPwdWindow() {
        final View contentView = LayoutInflater.from(this).inflate(R.layout.country_chooise, null);
        countryDalu = contentView.findViewById(R.id.country_dalu);
        countryMacao = contentView.findViewById(R.id.country_macao);
        countryHk = contentView.findViewById(R.id.country_hk);
        countryTw = contentView.findViewById(R.id.country_tw);
        countryOther = contentView.findViewById(R.id.country_other);

        if (popupWindow == null) {
            popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        }
        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true); //设置点击menu以外其他地方以及返回键退出
        popupWindow.setOutsideTouchable(true);   //设置触摸外面时消失
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        // 设置弹出窗体的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable(MyApplication.app.getResources(), (Bitmap) null));
        ColorDrawable cd = new ColorDrawable();
        popupWindow.setBackgroundDrawable(cd);
        //这句话，让pop覆盖在输入法上面
        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);

        // 5 在底部显示
        popupWindow.showAtLocation(contentView.findViewById(R.id.country_register_chooise),
                Gravity.CENTER, 0, 0);
        initLilstener();

    }

    /**
     * 監聽pup  国家区号
     */
    private void initLilstener() {
        /**
         * 點擊大陸
         */
        countryDalu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countryCode = "0";
                s = countryDalu.getText().toString();
                tvCountryName.setText(s);
                tvNumberPhone.setText("+86");
                img = getResources().getDrawable(R.drawable.cn2x);
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight()); //设置边界
                tvCountryName.setCompoundDrawables(img, null, null, null);
                popupWindow.dismiss();
            }
        });
        /**
         * 點擊澳門
         */
        countryMacao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countryCode = "1";
                s = countryMacao.getText().toString();
                tvCountryName.setText(s);
                tvNumberPhone.setText("+853");
                img = getResources().getDrawable(R.drawable.mo2x);
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight()); //设置边界
                tvCountryName.setCompoundDrawables(img, null, null, null);
                popupWindow.dismiss();
            }
        });
        /**
         * 點擊香港
         */
        countryHk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countryCode = "2";
                s = countryHk.getText().toString();
                tvCountryName.setText(s);
                tvNumberPhone.setText("+852");
                img = getResources().getDrawable(R.drawable.hk2x);
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight()); //设置边界
                tvCountryName.setCompoundDrawables(img, null, null, null);
                popupWindow.dismiss();
            }
        });
        /**
         * 點擊台灣
         */
        countryTw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countryCode = "3";
                s = countryTw.getText().toString();
                tvCountryName.setText(s);
                tvNumberPhone.setText("+886");
                img = getResources().getDrawable(R.drawable.img_tw2x);
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight()); //设置边界
                tvCountryName.setCompoundDrawables(img, null, null, null);
                popupWindow.dismiss();
            }
        });
        /**
         * 點擊其他
         */
        countryOther.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countryCode = "4";
                s = countryOther.getText().toString();
                tvCountryName.setText(s);
                tvNumberPhone.setText("");
                img = getResources().getDrawable(R.drawable.other2x);
                img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight()); //设置边界
                tvCountryName.setCompoundDrawables(img, null, null, null);
                popupWindow.dismiss();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!btnRegisterNumber.isFinish()) {
            btnRegisterNumber.cancel();
        }
    }

    @Override
    public void showVerticationDataSuccess(RegisterVerticationBean registerVerticationBean) {
        //  发送验证码请求成功后调用
        btnRegisterNumber.start();
        hideProgressDialog();
        SpUtils.putString(MyApplication.app, Constants.IPHONE, registerVerticationBean.getRegisterSmsnum());
        SpUtils.putString(MyApplication.app, Constants.VERTIFICATION_CODE, registerVerticationBean.getRandomNum());
        LogUtils.e("" + registerVerticationBean.getRandomNum());
//        ToastUtils.showToast(registerVerticationBean.getRandomNum());
        LogUtils.e("phone==" + registerVerticationBean.getRegisterSmsnum());
        LogUtils.e("shouji=======" + registerVerticationBean.getId());
        Timer timer = new Timer(true);
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                SpUtils.remove(MyApplication.app, Constants.VERTIFICATION_CODE);
                //  LogUtils.e("zoulezheli==========="+Constants.VERTIFICATION_CODE);
            }
        };
        timer.schedule(task, 600000);

        DialogUIUtils.showAlert(this, "验证码", registerVerticationBean.getRandomNum(), "", "", "确定", "", true, true, true, new DialogUIListener() {
            @Override
            public void onPositive(CharSequence input1, CharSequence input2) {

            }

            @Override
            public void onNegative(CharSequence input1, CharSequence input2) {

            }
        }).show();
    }

    @Override
    public void showNetworkError() {

    }


    @OnClick({R.id.changepassword_back, R.id.tv_country_name, R.id.btn_register_number, R.id.register_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.changepassword_back:
                finish();
                break;
            case R.id.tv_country_name:
                inputOtherPwdWindow();
                break;
            case R.id.btn_register_number:
                //这里判断是否倒计时结束，避免在倒计时时多次点击导致重复请求接口
                if (btnRegisterNumber.isFinish()) {//完成才調用
                    if (!phoneRegister.getText().toString().trim().equals("")) {
                        showProgressDialog("正在獲取...");
                        if (countryCode.equals("1")) {
                            mPresenter.getVerticatinCode(("meg" + phoneRegister.getText().toString().trim()), deviceUid, "android",
                                    phoneRegister.getText().toString().trim(), countryCode, "1"); //flag=0/1 0就是第一次注册时传
                        } else {
                            mPresenter.getVerticatinCode(("meg" + tvNumberPhone.getText().toString() + phoneRegister.getText().toString().trim()), deviceUid, "android",
                                    (tvNumberPhone.getText().toString().trim() + phoneRegister.getText().toString().trim()), countryCode, "1"); //flag=0/1 0就是第一次注册时传
                        }
                    } else {
                        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);//加载动画资源文件
                        btnRegisterNumber.startAnimation(shake);
                        phoneRegister.startAnimation(shake);
                        TipHelper.Vibrate(this, 100);
                        ToastUtils.showToast("手机号码不能为空！");
                    }
                } else {
                    ToastUtils.showToast("別著急哦");
                }
                break;
            case R.id.register_next:
                if (!phoneRegister.getText().toString().trim().equals("") && !getNumber.getText().toString().trim().equals("")) {
                    ver = SpUtils.getString(this, Constants.VERTIFICATION_CODE, "");
                    if (!ver.equals("")) {
                        if (getNumber.getText().toString().trim().equals(SpUtils.getString(this, Constants.VERTIFICATION_CODE, ""))) {
                            if (!btnRegisterNumber.isFinish()) {
                                btnRegisterNumber.cancel();
                            }
                            startActivity(ForgotNextActivity.class);
                            finish();
                        } else {
                            ToastUtils.showToast(R.string.error_vertification_code);
                            getNumber.setHint(R.string.error_vertification_code);
                        }
                    } else {
                        ToastUtils.showToast("验证码已过期,请重新获取");
                        return;
                    }
                } else {
                    ToastUtils.showToast(getString(R.string.empty_number));
                }
                break;
        }
    }
}
